package org.stayfool.auth.shiro;

import javax.annotation.Resource;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.stayfool.auth.common.util.StringUtil;
import org.stayfool.auth.entity.auth.AppUser;
import org.stayfool.auth.service.AuthService;
import org.stayfool.auth.util.PasswordUtil;

public class WebRealm extends AuthorizingRealm {

	@Resource(name = "authService")
	private AuthService authService;

	// 认证
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken)
			throws AuthenticationException {

		String userName = null;
		if (authenticationToken instanceof UsernamePasswordToken) {
			userName = ((UsernamePasswordToken) authenticationToken).getUsername();
		} else if (authenticationToken.getPrincipal() != null) {
			userName = authenticationToken.getPrincipal().toString();
		}

		if (StringUtil.isNullOrEmptyWithTrim(userName))
			throw new UnknownAccountException("invalid username！");

		AppUser user = authService.getUserByName(userName);

		if (user == null)
			throw new UnknownAccountException();
		else if (user.getIsLocked())
			throw new LockedAccountException();

		return new SimpleAuthenticationInfo(user, user.getPassword(), PasswordUtil.convert(user.getSalt()), getName());
	}

	// 授权
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
		// TODO Auto-generated method stub
		// 根据用户配置权限
		if (principalCollection == null) {
			throw new AuthorizationException("PrincipalCollection method argument cannot be null");
		}
		AppUser user = (AppUser) getAvailablePrincipal(principalCollection);

		SimpleAuthorizationInfo rt = new SimpleAuthorizationInfo();
		rt.addRoles(authService.getRoles(user.getUsername()));
		rt.addStringPermissions(authService.getPermissions(user.getUsername()));
		return rt;
	}

}
